<template>
    <div>
        <el-row>
            <el-col :span="8" align="left">
                <span>消息ID：</span>
                <el-input placeholder="请输入消息ID" v-model="msgId" clearable style="width:50%;"></el-input>
            </el-col>
            <el-col :span="8" align="left">
                <span>标题：</span>
                <el-input placeholder="请输入标题" v-model="msgTitle" clearable></el-input>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="4" align="left">
                <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>
            </el-col>
            <el-col :span="16"></el-col>
            <el-col :span="4" align="right">
                <el-button type="primary" icon="el-icon-plus" @click="add">新增消息</el-button>
            </el-col>
        </el-row> 
        <el-table
              :data="table"
              v-loading="tableLoading"
              border
              stripe 
              size="small"
              height="500"
              style="width: 100%">
            <el-table-column
                label="消息ID"
                fixed="left"
                prop="msgId"
                align="center"
                width="100">
            </el-table-column>
            <el-table-column
                label="标题"
                fixed="left"
                prop="msgTitle"
                align="center"
                :show-overflow-tooltip="true"
                width="200">
            </el-table-column> 
            <el-table-column
                label="图片地址"
                prop="picUrl"
                align="center"
                :show-overflow-tooltip="true"
                width="200">
            </el-table-column> 
            <el-table-column
                label="标签"
                prop="msgLabel"
                align="center"
                width="120">
            </el-table-column> 
            <el-table-column
                label="内容"
                prop="msgContent"
                align="center"
                :show-overflow-tooltip="true"
                width="200">
            </el-table-column>
            <el-table-column
                label="创建时间"
                prop="createdTime"
                align="center"
                width="200">
            </el-table-column>
            <el-table-column
                label="发布时间"
                prop="publishedTime"
                align="center"
                width="200">
            </el-table-column>
            <el-table-column
                label="更新时间"
                prop="updatedTime"
                align="center"
                width="200">
            </el-table-column>
            <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="200">
            <template slot-scope="scope">
                <el-button type="warning" size="mini" style="padding: 8px;margin: 2px" 
                @click="edit(scope.row)">修改消息</el-button>
                <el-button style="padding: 8px;margin: 2px" type="danger"
                        size="mini" @click="deleteItem(scope.row)">删除消息
                </el-button>
            </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="currentChange"
            layout="prev, pager, next"
            :total="totalCount"
            style="margin:50px;">
        </el-pagination>
        <div style="margin:30px 0;" class="fw">共{{Math.ceil(totalCount/pageSize)}}页,{{totalCount}}条信息</div>
        <el-dialog :title="dialogTitle" :visible.sync="dialogShow"
            v-loading="dialogLoading" :close-on-click-modal="false" width="800px">
            <el-row style="height:auto">
                <el-col :span="4"></el-col>
                <el-col :span="16" style="height:auto">
                    <span>标题：</span>
                    <el-input type="textarea" :rows="2" placeholder="请输入标题" v-model="dialog.msgTitle" clearable></el-input>
                </el-col>
                <el-col :span="4"></el-col>
            </el-row>
            <el-row style="height:150px;" v-if="dialog.msgPic">
                <el-col :span="4"></el-col>
                <el-col :span="11">
                    <el-image
                        style="width: 150px; height: 150px"
                        :src="dialog.msgPic"
                        >
                    </el-image>
                </el-col>
                <el-col :span="4"></el-col>
            </el-row>
            <el-row>
                <el-col :span="4"></el-col>
                <el-col :span="16">
                    <span>图片：</span>
                    <el-input type="textarea" v-model="dialog.msgPic" :disabled="true" style="width:70%"></el-input>
                </el-col>
                <el-col :span="4">
                    <el-upload class="avatar-uploader" :http-request="uploadSectionFile" :show-file-list="false" action="http://118.89.154.192:8086/appTokenServer">
                    　　<el-button size="small" type="primary" :disabled="uploadLoading" :loading="uploadLoading">点击上传</el-button>
                    </el-upload>
                </el-col>
            </el-row> 
            <el-row>
                <el-col :span="4"></el-col>
                <el-col :span="16">
                    <span>标签：</span>
                    <el-input placeholder="请输入标签" v-model="dialog.msgLabel" clearable></el-input>
                </el-col>
                <el-col :span="4"></el-col>
            </el-row> 
            <el-row>
                <el-col :span="4"></el-col>
                <el-col :span="16">
                    <span>时间：</span>
                    <el-date-picker
                        v-model="dialog.publishedTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-col>
                <el-col :span="4"></el-col>
            </el-row>
            <el-row style="height:auto">
                <el-col :span="4"></el-col>
                <el-col :span="2" align="right"><span>内容：</span></el-col>
                <el-col :span="16" style="height:auto">
                    <el-upload class="avatar-uploader" :http-request="uploadContentFile" :show-file-list="false" action="http://118.89.154.192:8086/appTokenServer">
                        <el-button id="article-uploader" size="small" type="primary" style="display:none">点击上传</el-button>
                    </el-upload>
                <div class="ql-container ql-snow">
                    <quill-editor ref="text" v-model="dialog.msgContent"
                     class="ql-editor" :options="editorOption" v-loading="uploadLoading"/>
                </div>
                </el-col>
                <el-col :span="2"></el-col>
            </el-row>
            <el-row>
                <el-col :span="6"></el-col>
                <el-col :span="10"></el-col>
                <el-col :span="8">
                    <el-button type="primary" @click="sureAdd">确定</el-button>
                    <el-button type="danger" @click="dialogShow=false">取消</el-button>
                </el-col>
            </el-row> 
        </el-dialog>
    </div>
</template>
<script>
let OSS = require('ali-oss');
let client = new OSS({
  region: 'oss-cn-shanghai',
  //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
  accessKeyId: 'LTAIoM90JOn4aEwU',
  accessKeySecret: 'OATKi5mcguNP3O4psil8uEuBT3a7kk',
  bucket: 'maitianyun',
});
// 工具栏配置
const toolbarOptions = [
    ["bold", "italic", "underline", "strike"],     // 加粗 斜体 下划线 删除线
    ['blockquote', 'code-block'],                  // 引用  代码块
    [{'header': 1}, {'header': 2}],                // 1、2 级标题
    [{'list': 'ordered'}, {'list': 'bullet'}],     // 有序、无序列表
    // [{ script: "sub" }, { script: "super" }],   // 上标/下标
    [{'indent': '-1'}, {'indent': '+1'}],          // 缩进
    [{'direction': 'rtl'}],                        // 文本方向
    [{'size': ['small', false, 'large', 'huge']}], // 字体大小
    [{'header': [1, 2, 3, 4, 5, 6, false]}],       //标题
    [{'color': []}, {'background': []}],           // 字体颜色、字体背景颜色
    [{'font': []}],                                //字体种类                    
    [{'align': []}],                               //对齐方式
    ['image'],                                     // 链接link、图片、视频video
    ['clean']                                      // 清除文本格式
]
let quill;
export default {
    data(){
        return{
            msgId:"",
            msgTitle:"",
            tableLoading:false,
            table:[],
            currentPage: 1,
            pageSize: 20,
            totalCount: 0,
            dialogTitle:"",
            dialogShow:false,
            dialogLoading:false,
            dialog:{
                msgId:"",
                msgTitle:"",
                msgPic:"",
                msgLabel:"",
                publishedTime:"",
                msgContent:"",
            },
            uploadLoading:false,
            editorOption: {                
                modules: {
                    toolbar: {
                        container: toolbarOptions,  // 工具栏
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    // 调用自定义图片上传
                                    //等于点击上传按钮被点击
                                    document.querySelector('#article-uploader').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },
        }
    },
    mounted(){
        this.initData()
    },
    methods:{
        requestInfo(){
            this.tableLoading=true;
            this.postRequest("/api/background/message_info/message_info_mg", {
                msgId:this.msgId,
                msgTitle:this.msgTitle,
                pageIndex: this.currentPage,
                pageSize: this.pageSize
            })
            .then(resp => {  
                this.tableLoading=false;
                if (resp && resp.data.status == 200){
                    this.table=resp.data.obj.rows;
                    this.totalCount = resp.data.obj.total;
                }
            });
        },
        initData(){
          this.requestInfo()
        },
        search(){
            this.currentPage = 1;
            this.requestInfo()
        },
        //列表当前页改变
        currentChange: function(currentChange) {
            this.currentPage = currentChange;
            this.requestInfo()
        },
        add(){
            this.dialogTitle="新增消息";
            this.dialogShow=true;
            this.msgInfoInit();
        },
        edit(item){
            this.dialogTitle="修改消息";
            this.dialogShow=true;
            this.dialog=item;
        },
        deleteItem(item){
            this.$confirm("此操作将删除该消息, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
            .then(() => {
            this.tableLoading=true;
            this.deleteRequest("/api/background/message_info/delete_message_info?msgId="+item.msgId).then(resp => {
                this.tableLoading=false;
                if (resp && resp.data.status == 200) {
                    this.common.showToast("success", resp.data.msg);
                    this.initData();
                }
            });
            })
            .catch(() => {});
        },
        timestamp(){
            var time = new Date();
            var y = time.getFullYear();
            var m = time.getMonth()+1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return ""+y+this.add0(m)+this.add0(d)+this.add0(h)+this.add0(mm)+this.add0(s);
        },
        add0(m){
            return m<10?'0'+m : m;
        },
        //上传图片
        uploadSectionFile(e){
            var file=e.file;
            if((file.type).indexOf("image")==-1){
                this.common.showToast("warning","只能上传图片")
            }else{
                this.dialogLoading=true;
                var value = file.name;
                var suffix = value.substr(value.indexOf("."));
                var storeAs = "image/"+this.timestamp()+suffix;
                console.log(file.name + ' => ' + storeAs);
                client.put(storeAs, file).then(r1 =>{
                    console.log(r1);
                    this.dialogLoading=false;
                    if(r1.res && r1.res.statusCode==200){
                        this.dialog.msgPic=r1.url;
                        // return client.get(storeAs);
                    }else{
                        this.common.showToast("warning","上传失败")   
                    }  
                }).then(function (r2) {
                    console.log(r2);
                }).catch(function (err) {
                    console.error(err);
                    this.dialogLoading=false;
                    this.common.showToast("warning","上传失败")
                });
            }
        },
        //富文本框上传图片
        uploadContentFile(e){
            var file=e.file;
           if((file.type).indexOf("image")==-1){
                this.common.showToast("warning","只能上传图片")
           }else{
                this.uploadLoading=true;
                var value = file.name;
                var suffix = value.substr(value.indexOf("."));
                var storeAs = "image/"+this.timestamp()+suffix;
                console.log(file.name + ' => ' + storeAs);
                client.put(storeAs, file).then(r1 =>{
                    console.log(r1);
                    if(r1.res && r1.res.statusCode==200){
                        // return client.get(storeAs);
                        // 获取富文本组件实例
                        quill = this.$refs.text.quill;
                        // 获取整个富文本长度
                        let length = quill.getLength();
                        // 获取整个富文本文子长度
                        // let textLength=quill.getText().length;
                        //获取当前所选择的下标
                        let selectIndex=quill.getSelection().index
                        // 插入图片
                        quill.insertEmbed(selectIndex, 'image', r1.url);
                        // 调整光标到最后
                        // quill.setSelection(length +1);
                        this.uploadLoading=false;
                    }else{
                        this.uploadLoading=false;
                        this.common.showToast("warning","上传失败")   
                    }  
                }).then(function (r2) {
                    // console.log(r2);
                }).catch(function (err) {
                    console.error(err);
                    this.uploadLoading=false;
                    this.common.showToast("warning","上传失败")
                });       
           }       
        },
        sureAdd(){
            if(this.common.isNull(this.dialog.msgTitle)){
                this.common.showToast('info','请填写标题')
            }else if(this.common.isNull(this.dialog.msgContent)){
                this.common.showToast('info','请填写内容')
            }else{
                this.dialogLoading=true;
                this.putRequest("/api/background/message_info/edit_message_info",{
                    msgId:this.dialog.msgId,
                    msgTitle:this.dialog.msgTitle,
                    picUrl:this.dialog.msgPic,
                    msgLabel:this.dialog.msgLabel,
                    publishedTime:this.dialog.publishedTime,
                    msgContent:this.dialog.msgContent,
                }).then(resp=>{
                    this.dialogLoading=false;
                    if(resp && resp.data.status == 200){
                        this.dialogShow=false;
                        this.msgInfoInit();
                        this.common.showToast('success','修改成功')
                        this.requestInfo()
                    }
                })
            } 
        },
        msgInfoInit(){
            this.dialog={
                msgId:"",
                msgTitle:"",
                msgPic:"",
                msgLabel:"",
                publishedTime:this.getNowFormatDate(),
                msgContent:"",
            }
        },
        //获取当前时间
        getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1<10? "0"+(date.getMonth() + 1):date.getMonth() + 1;
            var strDate = date.getDate()<10? "0" + date.getDate():date.getDate();
            var hours = date.getHours()<10? "0" +date.getHours():date.getHours();
            var minutes = date.getMinutes()<10? "0" +date.getMinutes():date.getMinutes();
            var seconds = date.getSeconds()<10? "0" +date.getSeconds():date.getSeconds();
            var currentdate = date.getFullYear() + seperator1  + month  + seperator1  + strDate
                    + " "  + hours  + seperator2  + minutes + seperator2 + seconds;
            return currentdate;
        }
        // exports(){
        //     console.log(searchInfo)
        //     var address=`/api/report/yun_xiang_hui/yun_xiang_hui_export?idCard=${searchInfo.idCard}&&customerName=${searchInfo.customerName}&&telPhone=${searchInfo.telPhone}&&startBankReceivedDate=${searchInfo.startBankReceivedDate}&&endBankReceivedDate=${searchInfo.endBankReceivedDate}`
        //     this.common.downloadFile(address); 
        // }
    }
}
</script>
<style scoped>
.el-row {
  margin-bottom: 30px;
  height: 50px;
  line-height: 50px;
}
.el-col {
  height: 50px;
  line-height: 50px;
}
.el-input,.el-textarea{
    width: 70%;
}
.ql-snow.ql-toolbar{
    position: absolute !important;
    background-color: #fff !important;
    z-index: 2 !important;
    top: 0;
}
.ql-editor{
    height: 300px;
    overflow-y: scroll;
}
.ivu-upload {
    display: none;
}

</style>